package com.app.couponsharelife.ui.main.home.good

import android.annotation.SuppressLint
import android.content.*
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.view.View
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.ImageShareBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.databinding.ActivityGoodShareBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.GoodSharePicAdapter
import com.app.couponsharelife.ui.dialog.BotShareDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.view.GoodSharePicView
import com.app.couponsharelife.ui.viewmodel.HomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import com.tencent.mm.opensdk.openapi.IWXAPI
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_good_share.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.io.File
import java.io.Serializable
import java.text.DecimalFormat
import java.util.*

class GoodShareActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_good_share

    private var goodBean: TaobaoGoodBean? = null

    private var mViewModel: HomeViewModel? = null

    private var picFile: File? = null

    private var api: IWXAPI? = null

    private var mTaoKouLing = ""

    private var mShareUrl = ""

    private var appShareUrl=""

    private var picBitmapUriMap: HashMap<String, Uri> = HashMap()

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        if (intent!!.getSerializableExtra("good") != null)
            goodBean = intent!!.getSerializableExtra("good") as TaobaoGoodBean
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        initToolBar()
        initTextView()
        initRecyclerView()
        initClickEvent()
    }

    private fun initToolBar() {
        (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = PageTipBean("", 0, 0)
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "商品分享"
    }

    private fun initTextView() {
        val df = DecimalFormat("#0.00")
        tvGoodName.text = goodBean?.title
        tvGoodOriginalPrice.text = df.format(goodBean?.original_price?.toDouble())
        tvGoodCouponPriceTitle.text = if (goodBean!!.has_coupon) "券后：" else "抢："
        tvGoodCouponPrice.text = df.format(goodBean?.final_price?.toDouble())
        tvDownloadAppTip.text = String.format("下载APP：立赚%s元", df.format(goodBean?.vip_commission?.toDouble()))
        tvGoodEvaluateProfit.text = String.format("返¥%s", df.format(goodBean?.vip_commission?.toDouble()))
    }

    private fun initRecyclerView() {
        val data = arrayListOf<ImageShareBean>()
        if (goodBean!!.images.isNotEmpty()) {
            for (item in goodBean!!.images) data.add(ImageShareBean(item))
        } else {
            if (goodBean!!.pict_url is String)
                data.addAll(arrayListOf(ImageShareBean(goodBean!!.pict_url as String)))
        }
        mRecyclerView.layoutManager = GridLayoutManager(this, 2)
        mRecyclerView.adapter = GoodSharePicAdapter(data, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                if (arg1 == 0)
                    goScanPic(arg2 as Int)
            }
        })
        (mRecyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
    }

    private fun goScanPic(arg1: Int) {
        val intent = Intent(this, ScanPicActivity::class.java)
        val list = arrayListOf<Any>()
        if (picFile != null)
            list.add(picFile!!)
        for (item in (mRecyclerView.adapter as GoodSharePicAdapter).list)
            list.add((item as ImageShareBean).image!!)
        intent.putExtra("pics", list as Serializable)
        intent.putExtra("position", arg1 + 1)
        startActivity(intent)
    }

    private fun initClickEvent() {
        (mViewDataBinding as ActivityGoodShareBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.ivSharePic -> {
                    goScanPic(-1)
                }
                R.id.tvCopyTaobaoLink -> {
                    when {
                        "拼多多"==goodBean!!.goodsSource -> {
                            copyGoodsText()
                        }
                        "京东"==goodBean!!.goodsSource -> {
                            copyGoodsText()
                        }
                        else -> //复制分享文字
                            copyText()
                    }
                }
                R.id.tvShareGoodPic -> {
                    //showShare()
                    //shareSingleBitmap(0)
                    BotShareDialog(this, R.style.DialogStyle, object : OnClickListener {
                        override fun click(arg1: Int, arg2: Any) {
                            when {
                                (mRecyclerView.adapter as GoodSharePicAdapter).num > 1 -> {
                                    //Log.e("eeee","--->分享多图")
                                    if (arg1>0){
                                        showToastMsg("朋友圈暂不支持分享多张图片！")
                                    }else{
                                        shareMultiBitmap(arg1)
                                    }
                                }
                                (mRecyclerView.adapter as GoodSharePicAdapter).num == 1 -> {
                                    shareSingleBitmap(arg1)
                                }
                                else -> showToastMsg("请选择要分享的图片")
                            }
                        }
                    }).show()

                }
            }
        }
    }

    private fun shareMultiBitmap(type: Int) {
        if (picFile != null) {
            showProgressDialog("请稍候")
            var intent = Intent()
            val comp = if (type == 0)
                ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
            else
                ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
            intent.component = comp
            intent.action = Intent.ACTION_SEND_MULTIPLE
            intent.type = "image/*"
            when {
                "拼多多"==goodBean!!.goodsSource -> {
                    copyGoodsText()
                }
                "京东"==goodBean!!.goodsSource -> {
                    copyGoodsText()
                }
                else -> //复制分享文字
                    copyText()
            }
//            intent.putExtra("Kdescription", tvShareText.text.toString())
            val imageUris = arrayListOf<String>()
            imageUris.add(picFile!!.path)
            /*if (picBitmapUriMap["shareImg0.jpg"] == null) {
                picBitmapUriMap["shareImg0.jpg"] = Uri.fromFile(picFile)
            }*/
            //imageUris.add(picBitmapUriMap["shareImg0.jpg"]!!)
            var index = 1
            for (item in (mRecyclerView.adapter as GoodSharePicAdapter).list) {
                if ((item as ImageShareBean).select && item.image is String && item.bitmap != null) {
                    /*if (picBitmapUriMap["shareImg$index.jpg"] == null) {
                        picBitmapUriMap["shareImg$index.jpg"] =
                                Uri.fromFile(AppUtils.saveBitmap(item.bitmap!!, "shareImg$index.jpg", false))
                    }
                    imageUris.add(picBitmapUriMap["shareImg$index.jpg"]!!)
                    index++*/
                    imageUris.add(Uri.fromFile(AppUtils.saveBitmap(item.bitmap!!, "shareImg$index.jpg", false)).path?:"")
                    //imageUris.add(item.image as String)
                    index++
                }
            }
            val imags= arrayOfNulls<String>(imageUris.size)
            for (i in 0 until imageUris.size){
                imags[i]=imageUris[i]
            }
            dismissProgressDialog()
            if (imageUris.isEmpty()) {
                showToastMsg("请选择要分享的图片")
                return
            }
            val sp= Platform.ShareParams()
            sp.shareType=Platform.SHARE_IMAGE
            sp.imageArray=imags
            val wechat = if (type == 1){
                ShareSDK.getPlatform (WechatMoments.NAME)
            }else{
                ShareSDK.getPlatform (Wechat.NAME)
            }
            wechat.platformActionListener=object :PlatformActionListener{
                override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                    //Log.e("eeee","--->完成")
                    dayShare()
                }

                override fun onCancel(p0: Platform?, p1: Int) {
                    //Log.e("eeee","--->取消")
                }

                override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                    //Log.e("eeee","--->${p0?.name}---->${p1}----->${p2!!.message}")
                }
            }
            wechat.share(sp)
            /*intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)
            intent = Intent.createChooser(intent, "商品分享")
            startActivity(intent)*/
            //dismissProgressDialog()
        } else
            showToastMsg("数据错误，请退出重试")
    }

    private fun shareSingleBitmap(type: Int) {
        if (picFile == null) {
            showToastMsg("数据错误，请退出重试")
            return
        }
        when {
            "拼多多"==goodBean!!.goodsSource -> {
                copyGoodsText()
            }
            "京东"==goodBean!!.goodsSource -> {
                copyGoodsText()
            }
            else -> //复制分享文字
                    copyText()
        }

        //进行分享
        val options=BitmapFactory.Options()
        options.inPreferredConfig=Bitmap.Config.RGB_565
        val bitmap =BitmapFactory.decodeFile(picFile!!.absolutePath,options)
        val sp= Platform.ShareParams()
        sp.shareType=Platform.SHARE_IMAGE
        sp.imageData=bitmap
        val wechat = if (type == 1){
            ShareSDK.getPlatform (WechatMoments.NAME)
        }else{
            ShareSDK.getPlatform (Wechat.NAME)
        }
        wechat.platformActionListener=object :PlatformActionListener{
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                //Log.e("eeee","--->完成")
                dayShare()
            }

            override fun onCancel(p0: Platform?, p1: Int) {
                //Log.e("eeee","--->取消")
            }

            override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                //Log.e("eeee","--->${p0?.name}---->${p1}----->${p2!!.message}")
            }
        }
        wechat.share(sp)
        /*val image = WXImageObject(bitmap)

        val msg = WXMediaMessage()
        msg.mediaObject = image

        val thumb = Bitmap.createScaledBitmap(bitmap, 150, 150, true)
        msg.thumbData = AppUtils.bmpToByteArray(thumb, true)

        val req = SendMessageToWX.Req()    //创建一个请求对象
        req.message = msg  //把msg放入请求对象中
        if (type == 1)
            req.scene = SendMessageToWX.Req.WXSceneTimeline    //设置发送到朋友圈
        else
            req.scene = SendMessageToWX.Req.WXSceneSession   //设置发送给朋友
        req.transaction = AppUtils.buildTransaction("img")  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        if (api == null) api = WXAPIFactory.createWXAPI(this@GoodShareActivity, Contacts.WECHAT_APP_ID)
        api!!.sendReq(req)   //如果调用成功微信,会返回true*/
    }
    private fun copyText() {
        val df = DecimalFormat("#0.00")
        //获取剪贴板管理器：
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", String.format("【%s】\n%s\n%s\n%s\n%s",
                goodBean!!.title,
                "【在售价】${df.format(goodBean!!.original_price.toDouble())}元",
                "【券后价】${goodBean!!.final_price}元",
                "--------------------\n复制这条消息\n$mTaoKouLing,打开【手机淘宝】查看详情","券享生活App邀请链接：$appShareUrl")
        )
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("分享文字已复制")
    }
    private fun copyGoodsText() {
        val df = DecimalFormat("#0.00")
        //获取剪贴板管理器：
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", String.format("【%s】\n%s\n%s\n%s",
                goodBean!!.title,
                "【在售价】${df.format(goodBean!!.original_price.toDouble())}元",
                "【券后价】${goodBean!!.final_price}元",
                "券享生活App邀请链接：$appShareUrl")
        )
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("分享文字已复制")
    }
    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        if (!mViewModel!!.getTaoKouLing()!!.hasObservers()) {
            mViewModel!!.getTaoKouLing()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetTaoKouLing(hashMapOf(), false)
                        (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate(it.error!!.message)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetTaoKouLing(hashMapOf(), false)
                        (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetTaoKouLing(hashMapOf(), false)
                        if (it.data!!.data!= "") {
                            mTaoKouLing = it.data.data.toString()
                            tvShareText.text = String.format("复制这条消息\n$mTaoKouLing,打开【手机淘宝】即可查看")
                            saveShareItemInfo()
                        } else {
                            (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("淘口令获取失败，请退出重试")
                        }
                    }
                }
            })
            mViewModel!!.saveShareItemInfo()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshSaveShareItemInfo(hashMapOf(), false)
                        (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate(it.error!!.message)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshSaveShareItemInfo(hashMapOf(), false)
                        (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshSaveShareItemInfo(hashMapOf(), false)
                        if (it.data!!.data != "") {
                            mShareUrl =it.data.data!!
                            initSharePic()
                        } else {
                            (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("分享链接获取失败，请退出重试")
                        }
                    }
                }
            })
        }
        when {
            "拼多多"==goodBean!!.goodsSource -> {
                tvShareText.visibility=View.GONE
                tvCopyTaobaoLink.text="复制商品信息"
                mShareUrl =goodBean!!.coupon_share_url
                initSharePic()
            }
            "京东"==goodBean!!.goodsSource -> {
                tvShareText.visibility=View.GONE
                tvCopyTaobaoLink.text="复制商品信息"
                mShareUrl =goodBean!!.coupon_share_url
                initSharePic()
            }
            else -> loadData()
        }
        getShareAppUrl()
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        map["text"] = goodBean!!.title.replace("@", "").replace("%","％")
        /*val url = if (goodBean!!.coupon_share_url_new!= "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }*/
        val url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }
        if (url == "") {
            showToastMsg("该商品暂时不能分享")
            finish()
        }
        map["url"] = url
        map["relationId"] = ""
        map["userId"] = AppUtils.getString(Contacts.USERID,"")
        map["logo"] = goodBean!!.pict_url as String
        map["timestamp"] = (System.currentTimeMillis()).toString()
        map["sign"] = AppUtils.getMapString(map)
        //map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel?.freshGetTaoKouLing(map, true)
    }

    private fun saveShareItemInfo() {
        val map = HashMap<String, String>()
        map["code"] = mTaoKouLing
        map["imgPath"] = goodBean!!.pict_url as String
        map["itemId"] = goodBean!!.num_iid
        map["newPrice"] = goodBean!!.final_price
        map["nick"]=goodBean!!.shop_title
        map["reservePrice"]=goodBean!!.reserve_price
        map["smallImages"]=Gson().toJson(goodBean!!.images) //goodBean!!.images.toString()
        map["couponInfo"]=goodBean!!.coupon_price
        map["pageSource"]="quan11"
        map["volume"]=(goodBean!!.volume?:"").replace("月销","")
        map["userType"]=when(goodBean!!.goodsSource){
            "淘宝"->{"0"}
            "天猫"->{"1"}
            "拼多多"->{"3"}
            "京东"->{"2"}
            else->{"0"}
        }
        map["couponCount"]=goodBean!!.coupon_remain_count?:"0"
        map["oldPrice"] = goodBean!!.original_price
        map["title"] = goodBean!!.title.replace("%","％")
//        map["type"] = "1"
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel?.freshSaveShareItemInfo(map, true)
    }
    private fun getShareAppUrl(){
        val map = HashMap<String, String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getShareAppUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        if (it.code==200){
                            appShareUrl=it.data!!
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    private fun dayShare(){
        val map = HashMap<String, String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.shareDay(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        if (it.code==200){
                            //appShareUrl=it.data!!
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    @SuppressLint("CheckResult")
    private fun initSharePic() {
        val shareurl=goodBean!!.coupon_share_url+"&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"
        val view = GoodSharePicView(mShareUrl, goodBean!!, this@GoodShareActivity)
        Glide.with(this).load(goodBean!!.pict_url)
                .downloadOnly(object : SimpleTarget<File>() {
                    override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                        view.setImage(resource)
                        Observable.just("")
                                .subscribeOn(Schedulers.io())
                                .observeOn(Schedulers.io())
                                .map {
                                    picFile = AppUtils.saveBitmap(view.generateBitmap(), "shareImg0.jpg", false)
                                }.subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe({
                                    Glide.with(this@GoodShareActivity).asBitmap()
                                            .apply(RequestOptions().centerCrop().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))// 不使用内存缓存 不使用磁盘缓存
                                            .load(picFile)
                                            .into(ivSharePic)
                                    (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = PageTipBean("", 0, 2)
                                }, {
                                    println(it.message)
                                    (mViewDataBinding as ActivityGoodShareBinding).pageTipBean = parseErrorDate("分享图片生成失败，请退出重试")
                                })
                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}
